package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MemberDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author qzh
 * @create 2020-01-29 2020/1/29
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Override
    public Member findByTelphone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    //分页查询会员信息
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//查询条件
        //完成分页查询 基于mybatis框架提供的分页助手插件完成'
        PageHelper.startPage(currentPage,pageSize);

        Page<Member> page = memberDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Member> rows = page.getResult();
        PageResult pageResult = new PageResult(total,rows);
        return pageResult;
    }

    //编辑会员信息
    @Override
    public void edit(Member member) {
        memberDao.edit(member);
    }

    //根据id查询会员信息
    @Override
    public Member findById(Integer id) {
        return memberDao.findById(id);
    }

    //根据id删除会员
    @Override
    public void delete(Integer id) {
        memberDao.deleteOrderByMemberId(id);
        memberDao.deleteById(id);
    }

    @Override
    public Map findMemberAndOrderByOrderId(Integer id) {
        return null;
    }

    //保存会员信息
    public void add(Member member) {

        String password = member.getPassword();
        if(password!=null) {
            password = MD5Utils.md5(password);
        }
        member.setPassword(password);
        memberDao.add(member);
    }

    //根据月份查询会员数量
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            String date = month + ".31";
            Integer count = memberDao.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }
}
